<?php
class storage
{
   var $config;
   var $connection;
   
    public function __construct($conf)
    {
        if(empty($conf))
        {
            die('Bad config file');
            return false;
        }
        $this->config = $conf;
        
        $this->connect($conf->dbhost,$conf->dbuser,$conf->dbpass,$conf->dbname);
        
    }
    
    
    private function connect($dbhost,$dbuser,$dbpass,$dbname,$dbtype = 'mysql')
    {
    	try {
    		$this->connection = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
    		$this->connection->exec('SET NAMES UTF8');
    	} catch (PDOException $e) {
    		print "Error!: " . $e->getMessage() . "<br/>";
    		die();
    	}
    	print 'Connection to database "'.$dbname.'" successfully!';
        
    }
    
    
    public function select($table, $conditions, $limit=null,$sort='DESC')
    {
    	if(!(is_array($conditions))){
    	    return false;
    	}
    	
    	if((!empty($conditions)))
    	{
    		$where = '';
	    	foreach ($conditions as $condition => $value)
	    	{
	    		$where .= $condition . '="'.$value.'" AND ';		
	    	}
	    	$where = substr($where, 0,strlen($where) - 5);
	    	$query = 'SELECT * FROM `'.$table.'` WHERE '.$where;
	    	
    	}
    	else
    	{
    		$query = 'SELECT * FROM `'.$table.'`';
    		
    	}
    	if ($limit !== null)
    	{
    		$query .= ' LIMIT '.$limit;
    	}
    	//$query = 'SELECT * FROM radiatory WHERE 1';
    	//var_dump($query);
    	
    	try{ 		 	
    	    $result = $this->connection->query($query);
    	    $rows = $result->fetchAll();
    	}catch (PDOException $e) {
    		print "Error!: " . $e->getMessage() . "<br/>";
    		die();
    	}
    	//var_dump($result);
        
        ///var_dump($row);
        return $rows;
    }
    
    
    public function insert($table, $insarray=array())
    {
    	
    	if (!((is_array($insarray))&&(!empty($insarray))))
    	{
    		print 'ERROR:wrong input data!';
    		return false;
    	}
    	$query = '';
    	$data = array();
    	$placeholders= array();
    	$fieldsstr = '';
    	$i = 0;
    	foreach ($insarray as $placeholder => $value)
    	{
    		$placeholders[$i] = $placeholder;
    		$fieldsstr .=
    		$data[$i] = $value;
            $i++;
    	}
    	$fieldsstr = implode($placeholders, ', ');
    	$datastr = implode($data, ', ');
    	
    	try{
    	    $insert = $this->connection->prepare("INSERT INTO radiatory (name, email) values (?, ?)");
    	    $insert->execute($data);
    	}catch (PDOException $e) {
    		print "Error!: " . $e->getMessage() . "<br/>";
    		die();
    	}
    	return true;
    	
    }
    	
    	
    
    
    
}

?>